<template>
    <div>
        <div v-if="props.row" style="position: relative; width: 80px;
  height: 80px;">
            <img :src="props.row" class="avatar" />
            <el-icon style="position: absolute;top: 10px;right: 10px;cursor: pointer;color: red;font-size: 24px;"
                @click="removeImg">
                <CircleClose />
            </el-icon>
        </div>
        <el-upload v-else class="avatar-uploader" action="#" :show-file-list="false"
            :before-upload="beforeAvatarUpload">
            <el-icon class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { deletePhoto } from '@/api/merchant.js'
import { ElMessage } from 'element-plus'
const props = defineProps({
    row: {
        type: String,
        default: '', // 默认值为一个空对象
    }
})
const emit = defineEmits(['OK'])
const PathUrl = reactive({
    url: import.meta.env.VITE_APP_API
})
const urlData = ref('')
onMounted(() => {
    urlData.value = props.row
})
// 文件上传
const beforeAvatarUpload = (file) => {
    // const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    // const isLt2M = file.size / 1024 / 1024 < 2; // 文件大小限制为2MB

    // if (!isJPGOrPNG) {
    //     ElMessage('上传头像图片只能是 JPG/PNG 格式!')
    //     // this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
    //     return false;
    // }
    // if (!isLt2M) {
    //      ElMessage('上传头像图片大小不能超过 2MB!')
    //     // this.$message.error('上传头像图片大小不能超过 2MB!');
    //     return false;
    // }
    // console.log(isJPGOrPNG,isLt2M)
    const formData = new FormData(); // 创建FormData对象用于发送表单数据
    formData.append('file', file); // 将文件添加到FormData对象中，键名为'file'（根据后端需求）
    axios.post(`${PathUrl.url}/commonUtil/addPhoto`, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': localStorage.getItem('satoken'),
            'satoken': localStorage.getItem('satoken')
        } // 设置正确的Content-Type头部信息
    }).then(response => {
        urlData.value = response.data;
        emit('OK', urlData.value)
        console.log('File uploaded successfully:', response); // 上传成功后的处理逻辑
    }).catch(error => {
        console.error('Error uploading file:', error); // 上传失败后的处理逻辑
    });
    return false; // 返回false阻止文件上传
}
// 删除头像
const removeImg = () => {
    let filename = props.row.split('/').pop(); // 提取文件名部分
    deletePhoto({ filename }).then(response => {
        urlData.value = ''; // 清空图片URL
        emit('OK', '') // 清空图片URL
    })
}
</script>

<style lang="scss" scoped>
.avatar {
    width: 100%;
    height: 100%;
}

::v-deep .avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

::v-deep.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

::v-deep .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>